package com.aimango.robot.server.core.handler;


import com.aimango.robot.server.core.http.HttpRequestHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.ServerHandshakeStateEvent;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 判断websocket消息类型
 */
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static final Logger logger = LoggerFactory.getLogger(TextWebSocketFrameHandler.class);

  @Override
  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt == ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
      // 如果握手成功，则从该 ChannelPipeline 中移除 HttpRequestHandler，因为不会接收到任何 HTTP 消息了
      ctx.pipeline().remove(HttpRequestHandler.class);
      channelGroup.add(ctx.channel());
      System.out.println(ctx.channel().remoteAddress()+"上线了!");
    } else {
      super.userEventTriggered(ctx, evt);
    }
  }

  @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("TextWebSocketFrameHandler异常！！！！！", cause);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        channelGroup.remove(ctx.channel());
        System.out.println(ctx.channel().remoteAddress()+"断开连接");
    }

}
